<template>
  <div class="app-container">
    <!-- 卡片 -->
    <el-card class="tree-card" shadow="hover">
      <!--头部-->
      <TreeItems :company-name="companyName" :type="2" />
      <hr>

      <!-- 内容部分 -->
      <!-- 树状图 -->
      <el-tree
        :highlight-current="true"
        :data="departs"
        :default-expand-all="true"
        class="custom-tree"
        :expand-on-click-node="false"
      >
        <template #default="{ data }">
          <TreeItems :data="data" @reload="getDepartmentFn" />
        </template>
      </el-tree>
    </el-card>
    <!-- 弹出层 -->
    <AddDept :all-departments="allDepartments" @reload="getDepartmentFn" />
  </div>
</template>

<script>
import { getDepartmentAPI } from '@/api/departments.js'
import TreeItems from './components/tree-items.vue'
import AddDept from './components/add-dept.vue'
import { formatTree } from '@/utils/tree.js'

export default {
  components: {
    TreeItems,
    AddDept
  },
  data() {
    return {
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        }
      ], // 部门结构数据
      companyName: '',
      allDepartments: []
    }
  },
  created() {
    this.getDepartmentFn()
  },
  methods: {
    async getDepartmentFn() {
      const res = await getDepartmentAPI()
      // 所有部门
      this.allDepartments = res.depts
      // 保存公司名
      this.companyName = res.companyName
      // console.time('测试时间')
      this.departs = formatTree(res.depts, '')

      /*
      // 取出一级部门
      const data = res.depts.filter(item => item.pid === '')
      // 取出子部门
      data.map((item, index) => {
        const obj = res.depts.find(item2 => item2.pid === item.id)
        if (obj) data[index].children = [obj]
      })
      this.departs = data
      */
      // console.timeEnd('测试时间')
    }
  }
}
</script>

<style scoped lang="scss">
.tree-card {
  font-size: 14px;
}
.potion {
  cursor: pointer;
}
.custom-tree {
  width: 100%;
}
</style>
